#include <iostream>
#include <mpi.h>

#include "FileManagement.h"
#include "CmdLineArgs.h"

CmdLineArgs::CmdLineArgs(int argc, char* argv[]) {
    specified_c_model = false;

    //! parse command line
    for(int n = 1; n < argc; n++) {
        if(strcmp(argv[n], "--input_file") == 0 || strcmp(argv[n], "-i") == 0) {     // input_file
            in_file = argv[++n];
        } else if(strcmp(argv[n], "--output_path") == 0 || strcmp(argv[n], "-o") == 0) {
            out_dir = argv[++n];
            if(out_dir[out_dir.length() - 1] != SWT_SLASH)
                out_dir += SWT_SLASH;

        } else if(strcmp(argv[n], "--output_final3D") == 0) {
            out_final_3D = true;
        } else if(strcmp(argv[n], "--raw") == 0) {
            raw = true;
        } else if(strcmp(argv[n], "--c_model") == 0 || strcmp(argv[n], "-m") == 0) {
            specified_c_model = true;
            c_model = argv[++n];
        } else if(strcmp(argv[n], "--output_iter_3D") == 0) {

        } else {
            std::cout << "unidentified parameter: " << argv[n] << "\n";
            exit(1);
        }
    }

    //! shortcut for W. Sun
    if(argc <= 1) {
        in_file = "D:\\mpibin\\inp\\Sea_small_server.in";
        out_dir = "D:\\mpibin\\data\\";
        raw = true;
        c_model = "D:\\mpibin\\vmodel\\Sea_small_server.vmdl";
    }
}


#ifdef USE_GNU_COMPILER
void CmdLineArgs::check_and_make_subdir() {
    //! it is shown in experiments that:
    //! (1) the program's working directory will be changed after checking and making subdirectories, which is undesired by programmers
    //! (2) this->out_dir will also be modified, and is not followed by a SWT_SLASH, which may lead to undesired concatenating results.
    //! Hence, an extra string manipulation is added at the end of this function to avoid this situation.

    char orig_working_dir[300];
    SWT_GetCurrentDirectory(orig_working_dir);

    char identifier[200];
    FILE* fp = fopen(in_file.c_str(), "r");
    while(!feof(fp)) {
        fgets(identifier, 200, fp);
        if(feof(fp))
            break;
    }
    fclose(fp);

    if(identifier[strlen(identifier) - 1] == '\n')          // which is possible when using fgets()
        identifier[strlen(identifier) - 1] = '\0';


    int proc_id;
    MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);

    //////////////////////////////////////////////
    // WT SUN added, 2021.4.14;
    //check if output path is valid;
#ifdef _SWT_WIN32_
    if(_access(out_dir.c_str(), 0) == -1) {
		   printf("The output path %s doesn't exist\n", out_dir.c_str());
		   exit(1);
    }
   if(specified_c_model && _access(c_model.c_str(), 0) == -1) {
       printf("The vel model file %s doesn't exist\n", c_model.c_str());
       exit(1);
   }
#else
    if(access(out_dir.c_str(),0) == -1) {
        printf("The output path %s doesn't exist\n", out_dir.c_str());
        exit(1);
    }
    if(specified_c_model && access(c_model.c_str(), 0) == -1) {
        printf("The vel model file %s doesn't exist\n", c_model.c_str());
        exit(1);
    }

#endif
    char outdir[_MAX_PATH] = {""};

    //if(proc_id==0)
    {
        //create data output dir for current job;
        char user_tag[_MAX_PATH] = {""}, domain_name[_MAX_PATH] = {""}, date[_MAX_PATH] = {""};
        gettime(date);
        swt_fun_util_create_code_tag(user_tag, NULL, domain_name);
        int dir_ok = fun_csaw_create_dir(out_dir.c_str(), identifier, proc_id, 1, outdir, domain_name, date);
        if(dir_ok != 1) {
            printf("Myid=%d\tCan't make dir '%s'\n", proc_id, out_dir.c_str());
            char l3_mark[_MAX_PATH] = {""};
            dir_ok = createdatadir(out_dir.c_str(), user_tag, identifier, l3_mark, outdir, 2, 1);
        }
        if(dir_ok != 1) {
            printf("create output file folder %s failed. Exit.\n", out_dir.c_str());
            exit(1);
        }
        //	cmd_arg->out_final_path.assign(outdir);
        //	printf("proc_id=%d\tcreate folder %s ok!\n",proc_id, cmd_arg->out_final_path.c_str());
    }

    out_dir.assign(outdir);
    out_dir += SWT_SLASH;

    printf("proc_id=%d\tcreate folder %s ok!\n", proc_id, out_dir.c_str());
    ////////////////////////////////////////////////////

    chdir(orig_working_dir);
}

#endif  // USE_GNU_COMPILER
